<?php

namespace app\admin\controller\financial;

use service\JsonService;
use app\common\model as M;

/**
 * 提现模块
 */
class Withdraw extends \app\admin\controller\AuthController
{
	public $model = '\app\common\model\Withdraw';

    use \traits\ShotcutControllerTrait;

    /**
     * 微信提现
     * @Author   FW
     * @DateTime 2021-07-01
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function wechat()
    {
    	$org_info = M\Organ::withAccount(M\WithdrawAccount::WD_WECHAT);
    	$this->assign('org_info' , $org_info);
    	return $this->fetch();
    }

    /**
     * 轮询微信账号是否扫码提交
     * @Author   FW
     * @DateTime 2021-07-02
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function query_wechat ()
    {
    	$data = M\WithdrawAccount::where([
    		'wd_type'    =>    M\WithdrawAccount::WD_WECHAT,
    		'org_id'     =>    $this->adminInfo['org_id'],
    		'is_valid'   =>    M\WithdrawAccount::WD_INVALID
    	])->find();

    	if ( empty($data) ) {
    		return JsonService::fail('empty');
    	}
    	return JsonService::successful('OK',$data);
    }

    /**
     * 删除未保存的微信账号
     * @Author   FW
     * @DateTime 2021-07-02
     * @Email    123763712@qq.com
     * @param    integer          $org_id [description]
     * @return   [type]                   [description]
     */
    public function delete_wechat ()
    {
    	$res = M\WithdrawAccount::where([
    		'wd_type'    =>    M\WithdrawAccount::WD_WECHAT,
    		'org_id'     =>    $this->adminInfo['org_id'],
    		'is_valid'   =>    M\WithdrawAccount::WD_INVALID
    	])->delete();

    	if ( $res === false ) {
    		return JsonService::fail('fail');
    	}
    	return JsonService::successful('OK');
    }

    /**
     * 保存提款帐号
     * @Author   FW
     * @DateTime 2021-07-05
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function save_wechat ()
    {
        $data = $this->request->post();

        ## 验证码校验
        if ( !\app\routine\model\SmsCode::CheckCode($data['phone'],$data['code']) ) return JsonService::fail('验证码验证失败');
        \app\routine\model\SmsCode::setCodeInvalid($data['phone'],$data['code']);

        $res = M\WithdrawAccount::saveOne([
            'wd_type'            =>    $data['wd_type'],
            'wd_reciver_name'    =>    $data['wd_reciver_name'],
            'wd_reciver_account' =>    $data['wd_reciver_account'],
            'wd_reciver_realname'=>    $data['wd_reciver_realname'],
            'org_id'             =>    $this->adminInfo['org_id'],
            'is_valid'           =>    M\WithdrawAccount::WD_VALID
        ]);

        if ( $res === false ) {
            return JsonService::fail('设置提现帐号失败');
        }
        return JsonService::successful('设置成功');
    }

    /**
     * 保存
     * @Author   FW
     * @DateTime 2021-07-05
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function save ()
    {
        $data = $this->request->post();

        if ( !isset($data['wd_type']) ) return JsonService::fail('提现类型不可为空');

        if ( !in_array($data['wd_type'],['wechat','alipay','bank']) ) return JsonService::fail('提现类型错误');

        $data['org_id'] = $this->adminInfo['org_id'];
        if ( $data['org_id'] <= 0 ) return JsonService::fail('机构信息错误');

        if ( !isset($data['amount']) || $data['amount'] <= 0 ) return JsonService::fail('提现金额错误');

        $org_info = M\Organ::get($data['org_id']);
        if ( $org_info->organ_status != 1 ) return JsonService::fail('机构已禁用，不可提现');

        ## 单笔金额限制
        if ( $data['amount'] < 1 ) return JsonService::fail('单笔最小金额不能低于1元');
        if ( $data['amount'] > $this->model::ITEM_MAX_AMOUNT_LMT ) return JsonService::fail('单笔最大金额不能超过'.$this->model::ITEM_MAX_AMOUNT_LMT);

        ## 机构当天累计金额限制
        $day_total_amt = $this->model::dayTotalAmount($data['org_id'] , $data['wd_type']);
        if ( $data['amount'] > $this->model::ITEM_SUM_AMOUNT_LMT ) return JsonService::fail('当日累计金额不能超过'.$this->model::ITEM_SUM_AMOUNT_LMT);

        if ( $org_info->organ_balance < $data['amount'] ) return JsonService::fail('余额不足，不可提现');

        $data['create_time'] = date('Y-m-d H:i:s');
        $data['status']      = 1;

        $this->model::beginTrans();
        try {
            ## 插入提现申请记录
            $res = $this->model::insert($data);
            if ( !$res ) {
                return JsonService::fail('提现申请失败【0981】');
            }

            ## 扣减机构可提余额
            ## @todo 如果提现失败需要退回
            $res = M\Organ::where('id' , $this->adminInfo['org_id'])->setDec('organ_balance',$data['amount']);
            if ( !$res ) {
                return JsonService::fail('提现申请失败【0982】');
            }

            $this->model::commitTrans();
            return JsonService::successful('发起成功，请耐心等待财务处理');
        } catch ( \Exception $e ) {
            $this->model::rollbackTrans();
            return JsonService::fail($e->getMessage());
        }

        $this->model::rollbackTrans();
        return JsonService::fail('发起失败');
    }
} //Class End